<?php 
class ServiceController extends CController
{
    public function actionGetContent()
    {
    	$appId = Yii::app()->request->getParam('appId');
    	$appKey = Yii::app()->request->getParam('appKey');
    	$modifiedDate = Yii::app()->request->getParam('modifiedDate');
    	  
        if(!empty($appId) && !empty($appKey) && $appKey==Application::model()->findByPk($appId)->app_key)
        {
	    	//header('Content-type: application/json');
			if(!empty($modifiedDate))
	    		$contents = Content::model()->findAllByAttributes(array('application_id'=>$appId), 'modified_date >= :date', array('date' => $modifiedDate));
		    else
		    	$contents = Content::model()->findAllByAttributes(array('application_id'=>$appId));

		    // Add extended attributes to Json feed.
		    $records = array();
		    foreach ($contents as $content) {
		    	//$childModel = new $content->contentType->name;
		    	//$childContent = $childModel->findByAttributes(array('content_id' => $content->id));	
		    	//if($childContent)
		    	//	array_push($records, array_merge($content->getAttributes(), array_diff_key($childContent->getAttributes(), array_flip(Content::$hiddenFields) )) );
		    	//else 
		    	array_push($records, array_merge($content->getAttributes(),$this->_addModuleRecords() ));
		    }	
	    	
	    	echo CJSON::encode($records);	    	
	  		Yii::app()->end();
        }else {
        	header("Status: 404 Not Found");        	
        }
    }
    
    private function _addModuleRecords()
    {
    	$modules = Module::model()->findAll(); //TODO Should be application specific... 
    	$moduleRecords = array();
    	foreach ($modules as $module)
    	{
    		$moduleItem = Yii::app()->getModule($module->name);
    		if(isset($moduleItem->HOOKS) && method_exists($moduleItem, HooksManager::HOOK_METHOD_NAME)  && in_array(HooksManager::getHooks(HooksManager::HOOK_SERVICE_API), $moduleItem->HOOKS))
    		{
    			array_push($moduleRecords, $moduleItem->hookAction(HooksManager::HOOK_SERVICE_API));
    		}
    	}
    	
    	$mergeRecords = array();
    	foreach ($moduleRecords as $items) {
    		$mergeRecords =array_merge($mergeRecords, $items);
    	}
    	return $mergeRecords;   
    }
}
?>